<?php


namespace console\controllers;

use common\helpers\DateHelper;
use Yii;
use yii\console\Controller;
use Exception;

class FollowReportController extends Controller
{

    /**
     * 跟进报表快照生成
     *
     * @author wangxiang
     * @param string $startDate
     * @param int $projectId
     * @throws \yii\console\Exception
     */
    public function actionIndex(string $startDate = '', $projectId = 0)
    {
        if (!$startDate) {
            // 因为任务是12点后执行， 每次执行是获取一整个月的数据
            // 先获取昨天的时间， 确定执行哪个月的数据
            $timeArea = DateHelper::aMonth(date('Y', strtotime('-1 day')), date('m', strtotime('-1 day')));
            $type = 'm';    // 执行整月
        } else {
            // 验证传入日期格式
            if (substr_count($startDate, '-') === 0) {
                $timeArea = DateHelper::aYear($startDate);
                $type = 'y';
            } else if (substr_count($startDate, '-') === 1) {
                $timeArea = DateHelper::aMonth(date('Y', strtotime($startDate)), date('m', strtotime($startDate)));
                $type = 'm';
            } else {
                throw new \yii\console\Exception('日期不合法，只支持年或年月', 500);
            }
        }
        $startTime = $timeArea['start'];
        $endTime = $timeArea['end'] > time() ? time() : $timeArea['end'];

        try {
            Yii::$app->services->followReport->generateReport($startTime, $endTime, $projectId, $type);
            echo date('Y-m-d H:i:s') . ' - success！' . PHP_EOL;
        } catch (Exception $exception) {
            echo '执行时间：' . date('Y-m-d H:i:s') . PHP_EOL;
            echo '开始时间：' . date('Y-m-d H:i:s', $startTime) . PHP_EOL;
            echo '结束时间：' . date('Y-m-d H:i:s', $endTime) . PHP_EOL;
            echo '错误信息：' . PHP_EOL . $exception->getMessage() . PHP_EOL . PHP_EOL;
        }
    }
}
